// For debug output to console
ControlPanel.debug = true;

function ControlPanel() {

	this.dprint("ControlPanel Constructor");
	
	this.objects = new Array();
	this.clipboard = [];

	this.domElem = $('<div id="control_panel" class="control_panel"></div>');
	$("#control_panel_container").append(this.domElem);

	this.initCloseAction();
	this.initTabbedView();
	this.initSaveDialog();
	this.initLoadDialog();
	
	this.initObjectControls();
	
	this.initKeyboardControls();
	
	this.initCssClassesPanel();
	this.initJavascriptPanel();
	
	this.fullRefresh();

}

ControlPanel.className = "ControlPanel";

// Singleton instance
ControlPanel._theControlPanel = null;
function theControlPanel() { return ControlPanel._theControlPanel; }

ControlPanel.prototype.initLoadDialog = function() {

	var obj = this;
	var formhtml = '<div id="load_form" title="Load Document">\
						<p id="validateTips">Choose your document</p>\
						<form>\
							<select id="exportdoclist"></select>\
						</form>\
					</div>';
					
	$("body").append($(formhtml));
	$("#load_form").dialog({
		bgiframe: true,
		autoOpen: false,
		height: 425,
		width: 400,
		modal: true,
		buttons: {
			'Load': function() {
				//alert("STUB: loaded!");
				
				var docValues = $("#exportdoclist").val().split("&");
		
				loadDocument( docValues[0], docValues[1] );
				obj.fullRefresh();
				
				$(this).dialog('close');
			},
			Cancel: function() {
				$(this).dialog('close');
			}
		},
		close: function() {
			
		}
	});


};

ControlPanel.prototype.initObjectControls = function() {

	//<div id="saveload_control_container" class="control_group_container"></div>\
	//<div id="addobject_control_container" class="control_group_container"></div>\

	$("#tab_objectControls").append('\
		<div id="export_control_container" class="control_group_container"></div>\
		<div id="nav_control_container" class="control_group_container"></div>\
		<div id="object_list_container" class="control_group_container"></div>\
		<div id="object_control_container" class="control_group_container"></div>\
		<div id="canvas_control_container" class="control_group_container"></div>\
	');
	
	$("#object_control_container").append('\
		<div id="object_header" class="control_header">Object: </div>\
		<div id="object_controls" class="control_group"></div>'
	);
	
	//this.initAddControls();
	this.initExportControls();
	this.initNavControls();
	
	$("#object_list_container").hide();
	$("#object_control_container").hide();
};

ControlPanel.prototype.initSaveDialog = function() {

	var obj = this;
	var formhtml = '<div id="save_form" title="Save Document">\
						<p id="validateTips">All form fields are required.</p>\
						<form>\
						<fieldset>\
							<label for="document_filename">Filename</label><br />\
							<input type="text" name="document_filename" id="document_filename" class="text ui-widget-content ui-corner-all" /><br />\
							<label for="document_category">Category</label><br />\
							<input type="text" name="document_category" id="document_category" class="text ui-widget-content ui-corner-all" /><br />\
							<label for="document_title">Title</label><br />\
							<input type="text" name="document_title" id="document_title" class="text ui-widget-content ui-corner-all" /><br />\
							<label for="document_author">Author</label><br />\
							<input type="text" name="document_author" id="document_author" value="" class="text ui-widget-content ui-corner-all" /><br />\
							<label for="document_description">Description</label><br />\
							<textarea name="document_description" id="document_description" class="text ui-widget-content ui-corner-all"></textarea><br />\
						</fieldset>\
						</form>\
					</div>';
					
	$("body").append($(formhtml));
	$("#save_form").dialog({
		bgiframe: true,
		autoOpen: false,
		height: 425,
		modal: true,
		buttons: {
			'Save': function() {
				
				if ($("#document_filename").val() != "") {
					saveDocument($("#document_filename").val());
					obj.fullRefresh();
					$(this).dialog('close');
				} else {
					alert("please enter a filename");
				}	
						
				
			},
			Cancel: function() {
				$(this).dialog('close');
			}
		},
		close: function() {
			
		}
	});
	


};

ControlPanel.prototype.initTabbedView = function() {
	this.domElem.append('\
		<ul>\
			<li><a href="#tab_objectControls">Object</a></li>\
			<li><a href="#tab_cssClasses">CSS Classes</a></li>\
			<li><a href="#tab_javascript">Javascript</a></li>\
		</ul>\
		<div id="always_controls">\
			<div id="toolbar_new_button" class="toolbar_button" title="New">\
				<span class="ui-icon ui-icon-document">\
			</div>\
			<div id="toolbar_open_button" class="toolbar_button" title="Open">\
				<span class="ui-icon ui-icon-folder-open">\
			</div>\
			<div id="toolbar_save_button" class="toolbar_button" title="Save">\
				<span class="ui-icon ui-icon-disk">\
			</div>\
			<div id="toolbar_insert_button" class="toolbar_button" title="Insert Document">\
				<span class="ui-icon ui-icon-script">\
			</div>\
			<div class="toolbar_button" style="border: none; width: auto; height: auto;">\
				<span class="ui-icon ui-icon-grip-dotted-vertical">\
			</div>\
			<div id="toolbar_add_button" class="toolbar_button" title="Add Object">\
				<span class="ui-icon ui-icon-plus">\
			</div>\
			<div id="toolbar_del_button" class="toolbar_button" title="Delete Object">\
				<span class="ui-icon ui-icon-close">\
			</div>\
			<div id="toolbar_cut_button" class="toolbar_button" title="Cut">\
				<span class="ui-icon ui-icon-scissors">\
			</div>\
			<div id="toolbar_copy_button" class="toolbar_button" title="Copy">\
				<span class="ui-icon ui-icon-copy">\
			</div>\
			<div id="toolbar_paste_button" class="toolbar_button" title="Paste">\
				<span class="ui-icon ui-icon-clipboard">\
			</div>\
			<div class="toolbar_button" style="border: none; width: auto; height: auto;">\
				<span class="ui-icon ui-icon-grip-dotted-vertical">\
			</div>\
			<div id="toolbar_exportview_button" class="toolbar_button" title="Preview">\
				<span class="ui-icon-camera">\
			</div>\
			<div id="toolbar_exportcode_button" class="toolbar_button" title="View HTML">\
				<span class="ui-icon-pencil">\
			</div>\
		</div>\
		<div id="tab_objectControls"></div>\
		<div id="tab_cssClasses"></div>\
		<div id="tab_javascript"></div>\
	');
	this.domElem.tabs();

	// Hide disabled toolbar buttons
	$("#toolbar_del_button").hide();
	$("#toolbar_cut_button").hide();
	$("#toolbar_copy_button").hide();

	var obj = this;
	
	$(".toolbar_button").hover(
		function() {
			$(this).addClass("hover");
		},
		function() {
			$(this).removeClass("hover");
		}
	);
	
	$("#toolbar_new_button").click(function() {
		
	});
	
	$("#toolbar_open_button").click(function() {
		$("#load_form").dialog('open');
	});
	
	$("#toolbar_save_button").click(function() {
		$("#document_filename").val(theLayoutDocument().filename);
		$("#document_title").val(theLayoutDocument().title);
		$("#document_author").val(theLayoutDocument().author);
		$("#document_description").val(theLayoutDocument().description);
	
		$('#save_form').dialog('open');
	});
	
	$("#toolbar_insert_button").click(function() {
		
	});
	
	$("#toolbar_add_button").click(function() {
		obj.dprint("Add object");
		
		var o = new CanvasObject($("#addObject_type_text").val());
		theCanvas().baseObject.addObject(o);
		
		//theCanvas().baseObject.setSelectedObject(o);
		theCanvas().baseObject.setSelectedObjects([o]);
		
		$("#canvas_container").focus();
	});
	
	$("#toolbar_duplicate_button").click(function() {
		obj.dprint("Duplicate object");
		
		
		if (theCanvas().baseObject.selectedObjects.length>0) {

			var newSelected = [];			
			for (var i in theCanvas().baseObject.selectedObjects) {
			
				var o = CanvasObject.buildFromJSON( theCanvas().baseObject.selectedObjects[i].toJSON() );
				theCanvas().baseObject.addObject(o);
				o.setAttribute("x", o.x + 10);
				o.setAttribute("y", o.y + 10);
				
				newSelected.push(o);
				
				//theCanvas().baseObject.setSelectedObject(o);
				//theCanvas().baseObject.setSelectedObjects( [o] );
			
			}
			
			theCanvas().baseObject.setSelectedObjects( newSelected );
		}
		
		$("#canvas_container").focus();
		
	});
	
	$("#toolbar_copy_button").click(function() {
		obj.dprint("Copy object");
		obj.clipboard = [];
		for (var i in theCanvas().baseObject.selectedObjects) {
			obj.clipboard.push(theCanvas().baseObject.selectedObjects[i]);
		}
		obj.dprint("Copied " + obj.clipboard.length + " objects");
		$("#canvas_container").focus();
	});
	
	$("#toolbar_paste_button").click(function() {
		obj.dprint("Paste object");
		var newSelected = [];			
		for (var i in obj.clipboard) {
		
			var o = CanvasObject.buildFromJSON( obj.clipboard[i].toJSON() );
			theCanvas().baseObject.addObject(o);
			o.setAttribute("x", o.x);
			o.setAttribute("y", o.y);
			
			newSelected.push(o);
			
			//theCanvas().baseObject.setSelectedObject(o);
			//theCanvas().baseObject.setSelectedObjects( [o] );
		
		}
		
		obj.dprint("Pasted " + newSelected.length + " objects");
		theCanvas().baseObject.setSelectedObjects( newSelected );
		
		$("#canvas_container").focus();
	
	});
	
	$("#toolbar_del_button").click(function() {
		for (var i in theCanvas().baseObject.selectedObjects) {
			theCanvas().baseObject.removeObject(theCanvas().baseObject.selectedObjects[i]);
		}
	});
	
	
	$("#toolbar_cut_button").click(function() {
		obj.dprint("Copy object");
		obj.clipboard = [];
		for (var i in theCanvas().baseObject.selectedObjects) {
			obj.clipboard.push(theCanvas().baseObject.selectedObjects[i]);
			theCanvas().baseObject.removeObject(theCanvas().baseObject.selectedObjects[i]);
		}
		obj.dprint("Cut " + obj.clipboard.length + " objects");
		$("#canvas_container").focus();
	});
	
	$("#toolbar_exportview_button").click(function() {
		obj.dprint("export document");
		
		
		if (obj.html_window != undefined) { obj.html_window.close(); }
		//if (obj.download_window != undefined) { obj.download_window.close(); }
		
		var dest = $("#export_dest").val();
		dest = (dest == "" ? "html/render_output.html" : dest);
		
		obj.html_window = window.open(dest, theCanvas().id+"htmlwindow", "");
		obj.html_window.onload = function() {
				
			// Inject style and html into document once it is loaded
			$(obj.html_window.document.body).append(
				"<style type=\"text/css\">\n" + 
					theCanvas().getBaseObject().dumpCss() + "\n\n" +
					theLayoutDocument().cssClasses + "\n" +
				"</style>\n" +
				"<input id='doc_uuid' type='hidden' value='" + Math.uuid() + "'>\n" +
				theCanvas().getBaseObject().dumpHtml()
			);

			// This is legacy code for when rendered prototypes would have a header and description 
			// info injected into the page.
			/*
			$(obj.html_window.document.body).append( 
				"<style type=\"text/css\">\n" + 
					theCanvas().getBaseObject().dumpCss() + "\n\n" +
					theLayoutDocument().cssClasses + "\n" +
				"</style>\n" +
				"<input id='doc_uuid' type='hidden' value='" + Math.uuid() + "'>\n" +
				theCanvas().getBaseObject().dumpHtml() +
				
				"<div class='prototype_header'>" +
				"<h1>prototype: "+$("#export_title").val()+"</h1>\n" + 
				"<h3>author: "+$("#export_author").val()+"</h3>\n" + 
				"</div>" + 
				"<div class='prototype_description'>"+
				"<b>description:</b> <br>"+$("#export_description").val()+"\n" + 
				"</div>" + 
				"<div class='comments_header'>Comments</div>\
				<div class='comments_container'></div>\
				<div class=\"feedback_container\">\
					<div class=\"feedback_tab\">Feedback...</div>\
					<div class=\"feedback_form\">\
						<form>\
							From:<br />\
							<input id=\"feedback_from\" type=\"text\" name=\"feedback_from\"><br />\
							Comment:<br />\
							<textarea id=\"feedback_comment\" class=\"feedback\" name=\"feedback_comment\"></textarea><br />\
							<input type=\"button\" value=\"Post\" id=\"sendfeedback_button\">\
						</form>\
					</div>\
				</div>\
				<div class=\"comments_tab\">\
					Hide Comments\
				</div>"
				
				);
				*/

			$(obj.html_window.document.body).append(
				"<script>\n" +
					theLayoutDocument().js + "\n" +
				"</script>"
			);
						
			obj.dprint("appending load elements call");			
			if (obj.html_window[theCanvas().getBaseObject().idName + "_elementsLoaded"] != undefined) {
				obj.html_window[theCanvas().getBaseObject().idName + "_elementsLoaded"]();
			} else {
				obj.html_window.eval('alert("no elementsLoaded function");');
			}
			
			// Feedback no longer used in rendered prototypes -Abel
			//obj.html_window["initFeedback"]();
				
		};
	});

	$("#toolbar_exportcode_button").click(function() {
		obj.dprint("export document");
		
		if (obj.text_window != undefined) { obj.text_window.close(); }
		
		obj.text_window = window.open("html/text_output.html", theCanvas().id+"textwindow", "");
		obj.text_window.onload = function() {
			//alert("Your Div is ready!");
			
			//$(obj.text_window.document.body).append( theCanvas().getBaseObject().dumpCss() );
			obj.text_window.document.write( "<pre>"+
				escapeHtml( "<style type=\"text/css\">\n" + 
					theCanvas().getBaseObject().dumpCss() + "\n\n" +
					theLayoutDocument().cssClasses + "\n" +
				"</style>\n" +
					theCanvas().getBaseObject().dumpHtml()) +  
				"</pre>" );
		};
	});
	
};

ControlPanel.prototype.initCloseAction = function() {

	/*
	$(window).unload(function() {
		if (!confirm("Close LayoutManager?")) {
			e.stopPropagation();
			e.stopImmediatePropagation();
			return false;
		}
	});
	*/
	
	window.onbeforeunload = function() {
		return "Are you sure?";
	};

}

ControlPanel.prototype.initCssClassesPanel = function() {
	$("#tab_cssClasses").append('\
		<div class="control_group_container" style="height: auto;">\
			<div class="control_header">CSS Classes</div>\
			<div id="cssClasses_controls" class="control_group">\
				<textarea id="textarea_editCssClasses" style="width: 100%; height: 500px;"></textarea>\
				<input type="button" id="apply_cssClasses" value="Apply" />\
			</div>\
	');
	
	$("#apply_cssClasses").click(function() {
		theLayoutDocument().cssClasses = $("#textarea_editCssClasses").val();
		$("#style_cssClasses").html(theLayoutDocument().cssClasses);
	});
	$("#textarea_editCssClasses").blur(function() {
		theLayoutDocument().cssClasses = $("#textarea_editCssClasses").val();
		$("#style_cssClasses").html(theLayoutDocument().cssClasses);
	});
};

ControlPanel.prototype.initJavascriptPanel = function() {
	$("#tab_javascript").append('\
		<div class="control_group_container" style="height: auto;">\
			<div class="control_header">Javascript</div>\
			<div id="javascript_controls" class="control_group">\
				<textarea id="textarea_editJavascript" style="width: 100%; height: 500px;"></textarea>\
				<input type="button" id="apply_javascript" value="Apply" />\
			</div>\
	');
	
	$("#apply_javascript").click(function() {
		theLayoutDocument().js = $("#textarea_editJavascript").val();
	});
	$("#textarea_editJavascript").blur(function() {
		theLayoutDocument().js = $("#textarea_editJavascript").val();
	});
}

ControlPanel.prototype.initKeyboardControls = function() {
	var obj = this;
	$(document).keydown(function(e) {
		obj.dprint(e.keyCode);
		if (e.keyCode == 18) {
			$("#control_panel_container").toggle();
			if ( $("#control_panel_container").is(":hidden") ) {
				$("#canvas_container").css("width", "100%");
			} else {
				obj.dprint($("#canvas_container").css("width"));
				obj.dprint("now 70");
				$("#canvas_container").css("width", "74%");
			}
		}
	});
};

ControlPanel.prototype.initAddControls = function() {
	this.dprint("initAddControls");
	
	var obj = this;
	
	/*
	$("#tab_objectControls").append( $('\
		<div id="addobject_control_container" class="control_group_container">\
			<div class="control_header">Create</div>\
			<div id="add_controls" class="control_group">\
				Object type: <input id="addObject_type_text" type="text" value="div"><br>\
				<input id="addobject_button" type="button" value="Add">\
				<input id="dupobject_button" type="button" value="Duplicate">\
				<input id="copyobject_button" type="button" value="Copy">\
				<input id="pasteobject_button" type="button" value="Paste">\
				<br>Examples:<br>\
				type => <i>input type=\'text\'</i><br>\
				type => <i>div</i>\
			</div>\
		</div>')
	);
	*/
	
	$("#addobject_control_container").append( $('\
		<div class="control_header">Create</div>\
		<div id="add_controls" class="control_group">\
			Object type: <input id="addObject_type_text" type="text" value="div"><br>\
			<input id="addobject_button" type="button" value="Add">\
			<input id="dupobject_button" type="button" value="Duplicate">\
			<input id="copyobject_button" type="button" value="Copy">\
			<input id="pasteobject_button" type="button" value="Paste">\
			<br>Examples:<br>\
			type => <i>input type=\'text\'</i><br>\
			type => <i>div</i>\
		</div>\
		')
	);
	
	$("#addobject_button").click(function() {
		obj.dprint("Add object");
		
		var o = new CanvasObject($("#addObject_type_text").val());
		theCanvas().baseObject.addObject(o);
		
		//theCanvas().baseObject.setSelectedObject(o);
		theCanvas().baseObject.setSelectedObjects([o]);
		
		$("#canvas_container").focus();
	});
	
	$("#dupobject_button").click(function() {
		obj.dprint("Duplicate object");
		
		
		if (theCanvas().baseObject.selectedObjects.length>0) {

			var newSelected = [];			
			for (var i in theCanvas().baseObject.selectedObjects) {
			
				var o = CanvasObject.buildFromJSON( theCanvas().baseObject.selectedObjects[i].toJSON() );
				theCanvas().baseObject.addObject(o);
				o.setAttribute("x", o.x + 10);
				o.setAttribute("y", o.y + 10);
				
				newSelected.push(o);
				
				//theCanvas().baseObject.setSelectedObject(o);
				//theCanvas().baseObject.setSelectedObjects( [o] );
			
			}
			
			theCanvas().baseObject.setSelectedObjects( newSelected );
		}
		
		$("#canvas_container").focus();
		
	});
	
	$("#copyobject_button").click(function() {
		obj.dprint("Copy object");
		obj.clipboard = [];
		for (var i in theCanvas().baseObject.selectedObjects) {
			obj.clipboard.push(theCanvas().baseObject.selectedObjects[i]);
		}
		obj.dprint("Copied " + this.clipboard.length + " objects");
		$("#canvas_container").focus();
	});
	
	$("#pasteobject_button").click(function() {
		obj.dprint("Paste object");
		var newSelected = [];			
		for (var i in obj.clipboard) {
		
			var o = CanvasObject.buildFromJSON( obj.clipboard[i].toJSON() );
			theCanvas().baseObject.addObject(o);
			o.setAttribute("x", o.x);
			o.setAttribute("y", o.y);
			
			newSelected.push(o);
			
			//theCanvas().baseObject.setSelectedObject(o);
			//theCanvas().baseObject.setSelectedObjects( [o] );
		
		}
		
		obj.dprint("Pasted " + newSelected.length + " objects");
		theCanvas().baseObject.setSelectedObjects( newSelected );
		
		$("#canvas_container").focus();
	
	});
}

ControlPanel.prototype.initNavControls = function() {
	
	var obj = this;

	/*
	$("#tab_objectControls").append( $(
		'<div class="control_group_container">\
			<div class="control_header">Object Hierarchy</div>\
			<div id="nav_controls" class="control_group">\
				<input id="nav_up_button" type="button" value="Go Up">\
				<input id="nav_down_button" type="button" value="Go Down">\
				<div id="nav_map"></div>\
			</div>\
		</div>') );
	*/
	
	$("#nav_control_container").append( $('\
		<div class="control_header">Object Hierarchy</div>\
		<div id="nav_controls" class="control_group">\
			<input id="nav_up_button" type="button" value="Go Up">\
			<input id="nav_down_button" type="button" value="Go Down">\
			<div id="nav_map"></div>\
		</div>\
	') );
	
	$("#nav_up_button").click(function() {
		obj.dprint("nav up!");
		
		var p = theCanvas().getBaseObject().getParent();
		if (p != null) {
			theCanvas().setBaseObject(p);
		} else {
			this.dprint("null parent!");
		}
	});
	
	$("#nav_down_button").click(function() {
		obj.dprint("nav down!");
		
		var c = theCanvas().getSelectedObject();
		if (c != null) {
			theCanvas().setBaseObject(c);
		} else {
			this.dprint("null selection");
		}
	});
	
};

ControlPanel.prototype.initExportControls = function() {


	var obj = this;

	var saveload_html = '\
		<div id="saveload_control_container" class="control_group_container">\
			<div class="control_header">Save/Load <img id="export_spinner" src="img/spinner.gif" /></div>\
			<div id="saveload_controls" class="control_group">\
				<input id="exportsave_button" type="button" value="Save">\
				<input id="exportsaveas_button" type="button" value="Save As..">\
				<input id="exportload_button" type="button" value="Load">\
				<input id="exportinsert_button" type="button" value="Insert">\
				<input id="exportdel_button" type="button" value="Delete">\
				<br>\
				Documents: <select id="exportdoclist"></select><br>\
				<table style="border: none;"><tbody>\
				<tr><td>Category: <td><input type="text" id="export_username" value="'+theLayoutDocument().category+'" /></tr>\
				<tr><td>Author: <td><input type="text" id="export_author" value="'+theLayoutDocument().author+'" /></tr>\
				<tr><td>Title: <td><input type="text" id="export_title" value="'+theLayoutDocument().title+'" /></tr>\
				<tr><td>Description: <td><input type="text" id="export_description" value="'+theLayoutDocument().description+'" /></tr>\
				</tbody></table>\
				<input type="button" id="exportrefresh_button" value="Refresh" />\
			</div>\
		</div>';
		
	var export_html = '\
			<div class="control_header">Export to HTML</div>\
			<div id="export_controls" class="control_group">\
				dest page: <input id="export_dest" type="text">\
				<input id="export_view" type="button" value="Render Document">\
				<input id="export_html" type="button" value="View HTML">\
			</div>';
			
	$("#export_control_container").append( $(export_html) );

	$("#export_spinner").hide();
	$("#exportdoclist").load("cgi/doclist.php");

	$("#exportrefresh_button").click(function() {
		//alert($("#export_username").val());
		$("#exportdoclist").load("cgi/doclist.php", 
				{ username: $("#export_username").val() },
				function() {
					
				});
	});

	$("#exportsave_button").click(function() {
	
		//alert( JSON.stringify( theCanvas().baseObject ));
		if (curDocName == "") {
			var docName = prompt("Enter document name: ", "doc name here");
			if (docName != null) {
				saveDocument(docName);
				obj.fullRefresh();
			}
		} else {
			saveDocument(curDocName);
			obj.fullRefresh();
		}
		
	
	});
	
	$("#exportsaveas_button").click(function() {
	
		$("#document_filename").val(theLayoutDocument().filename);
		$("#document_title").val(theLayoutDocument().title);
		$("#document_author").val(theLayoutDocument().author);
		$("#document_description").val(theLayoutDocument().description);
	
		$('#save_form').dialog('open');
	
		/*
		//alert( JSON.stringify( theCanvas().baseObject ));
		var docName = prompt("Enter document name: ", "doc name here");
		if (docName != null) {
			saveDocument(docName);
			obj.fullRefresh();
		}
		*/
	
	});
	
	$("#exportload_button").click(function() {
		
		$('#save_form').dialog('open');
		
		/*
		var docValues = $("#exportdoclist").val().split("&");
		//alert(docValues[0] + " " + docValues[1]);
		
		
		loadDocument( docValues[0], docValues[1] );
		obj.fullRefresh();
		*/
	});
	
	$("#exportinsert_button").click(function() {
		var docValues = $("#exportdoclist").val().split("&");
		insertDocument( docValues[0], docValues[1] );
		obj.fullRefresh();
	});
	
	$("#exportdel_button").click(function() {
		var confirmDelete = confirm("Are you sure you want to delete?");
		if (confirmDelete) {
			var docValues = $("#exportdoclist").val().split("&");
			
			deleteDocument( docValues[0], docValues[1] );
			obj.fullRefresh();
		}
		
	});

}

ControlPanel.prototype.loadObjectControls = function() {

	// TODO:
	// There is a bug when I would try and empty the object_controls as opposed
	// to removing it and remaking it.  
	// If you simply empty the div, a dangling space related to the tables would
	// be left over.  Could not figure out how to get rid of it -Abel
	// UPDATE: resolved...
	
	$("#object_controls").empty();
	$("#object_header").empty();
			
	// Get canvas' selected object
	var selectedObj = null;
	var selectedObjs = null;
	if (theCanvas() != null) { 
		//selectedObj = theCanvas().getBaseObject().getSelectedObject(); 
		selectedObjs = theCanvas().getBaseObject().selectedObjects;
	}
	
	if (selectedObjs != null && selectedObjs.length == 1) {
		selectedObj = selectedObjs[0];
		this.dprint("obj: " + selectedObj.id);
	
		$("#object_header").append("Object: " + selectedObj.id);
		
		// Create table of input controls
		var str = "<table><tbody>";
		
		str += '<tr class="control attr">\
					<td class="control_label">visible</td>\
					<td class="control_input"><input id="selected_visible_input" name="visible" type="checkbox"' + 
					(selectedObj.isVisible ? 'checked' : '') + '></td>\
				</tr>';
		
		
		
		str += '<tr class="control attr">\
					<td class="control_label">id</td>\
					<td class="control_input"><input id="selected_id_input" name="id" type="text" value="'+ selectedObj.idName + '"></td>\
				</tr>';
		//$("#object_controls").append( $(str) );
		
		str += '<tr class="control">\
					<td class="control_label">tag type</td>\
					<td class="control_input"><input id="selected_tagtype_input" name="tagtype" type="text" value="'+ selectedObj.tagType.replace(/\"/g, "&quot;") + '"></td>\
				</tr>';
		
		str += '<tr class="control">\
					<td class="control_label">tag properties</td>\
					<td class="control_input"><input id="selected_tagprops_input" name="tagtype" type="text" value="'+ selectedObj.tagProperties.replace(/\"/g, "&quot;") + '"></td>\
				</tr>';
		
		
		for (var i in selectedObj.attributes) {
			var attr = selectedObj.attributes[i];
			
			if (attr.name != "id" && attr.cssName != "") {
	
				str += '<tr class="control attr">\
						<td class="control_label">'+ i + '</td>\
						<td class="control_input"><input name="'+i+'" type="text" value="'+ attr.value + '"></td>\
					</tr>';			
			}
		
		}
		
		str += '<tr><td colspan=2><div class="control_header">+ Custom Css</div></td></tr>\
		 	<tr class="control">\
		 		<td><input id=css_attr type="text"></td>\
		 		<td><input id=css_value type="text"></td>\
		 	</tr>';
		
		str += '<tr><td colspan="2"><div class="control_header">Content</div></tr>\
			 		<tr><td colspan="2"><input id=content_input type="text" value="'+
			 			selectedObj.content + '"></td></tr>\
			 		<tr><td colspan="2"><div class="control_header">Css Classes</div></tr>\
			 		<tr><td colspan="2" style="color: green; font-size: 9px;">';
		
		for (var className in selectedObj.classes) {
			this.dprint("classname: " + className);
			str += className + " ";
		}
		
		str += '</td></tr>\
				<tr class="control"><td>Add Class:</td><td><input id=css_addclass type="text"></td></tr>\
				<tr class="control"><td>Remove Class:</td><td><input id=css_delclass type="text"></td></tr>\
			</tbody></table>';
		
		$("#object_controls").append( $(str) );

		//
		// Control I/O Handlers
		//		
		$("#selected_visible_input").each(function() {
			$(this).change(function(e) {
				var isChecked = ($("#selected_visible_input:checked").val() != null);
				selectedObj.setIsVisible(isChecked);
			});
		});
		
		//
		// Keyboard handlers for input boxes
		//
		$("#selected_id_input").each(function() {
			$(this).keydown(function(e) {
				var key = e.keyCode;
				if (key == 13) {
					var value = $(this).val();
				
					selectedObj.setId(value);
				}
			});
		});
		
		$("#selected_tagtype_input").keydown(function(e) {
			if (e.keyCode == 13) {
				var value = $(this).val();
				selectedObj.tagType = value;
			}
		});
		
		$("#selected_tagprops_input").keydown(function(e) {
			if (e.keyCode == 13) {
				var value = $(this).val();
				selectedObj.tagProperties = value;
			}
		});
		
		$("#content_input").keydown(function(e) {
			var key = e.keyCode;
			if (key == 13) {
				selectedObj.setContent($(this).val());
			}
		});
		
		$("tr.control.attr input").each(function() {
			$(this).keydown(function(e) {
				var key = e.keyCode;
				if (key == 13) {
					var key = $(this).attr("name");
					var value = $(this).val();
				
					selectedObj.setAttribute(key, value);
				}
			});
		});

		$("tr.control #css_addclass").keydown(function(e) {
			var key = e.keyCode;
			if (key == 13) {
				selectedObj.addClass($(this).val());
				$(this).val("");
			}
		});
		$("tr.control #css_delclass").keydown(function(e) {
			var key = e.keyCode;
			if (key == 13) {
				selectedObj.removeClass($(this).val());
				$(this).val("");
			}
		});
		
		$("#object_controls #css_value").keydown(function(e) {
			var key =e.keyCode;
			if (key == 13) {
				var key = $("#object_controls #css_attr").val();
				var value = $("#object_controls #css_value").val();
				
				selectedObj.setAttribute(key, value);
				theControlPanel().fullRefresh();
				$("#object_controls #css_attr").focus();
				
				//selectedObj.setCss(key, value);
			}
		});
	
	// Provide a different set of controls if multiple objects are selected
	} else if (selectedObjs != null && selectedObjs.length > 1) {
		
		$("#object_header").append("Objects:");
	
		var obj = this;		
		var str = "";
		
		obj.dprint("Loading multiple selected objs controls");

		str += '<table><tr class="control attr">\
				<td class="control_label">visible</td>\
				<td class="control_input"><input id="all_selected_visible_input" name="visible" type="checkbox" "' + 
					(selectedObjs[0].isVisible ? 'checked' : '') + '></td>\
			</tr></table>';
		
		
		str += '<fieldset style="text-align: center;"><legend>Align</legend>\
					<input type="button" id="button_alignleft" class="control_button align_left" />\
					<input type="button" id="button_aligncenter" class="control_button align_center" />\
					<input type="button" id="button_alignright" class="control_button align_right" />\
					<br>\
					<input type="button" id="button_aligntop" class="control_button align_top" />\
					<input type="button" id="button_alignmiddle" class="control_button align_middle" />\
					<input type="button" id="button_alignbottom" class="control_button align_bottom" />\
				</fieldset>\
				<fieldset style="text-align: center;"><legend>Distribute</legend>\
					<input type="button" id="button_disthorizcenters" class="control_button dist_horiz" />\
					<input type="button" id="button_disthorizspace" class="control_button dist_horiz_space" />\
					<br>\
					<input type="button" id="button_distvertspace" class="control_button dist_vert_space" />\
					<input type="button" id="button_distvertcenters" class="control_button dist_vert" />\
				</fieldset>';
		
		str += '<table><tbody>\
					<tr><td colspan="2"><div class="control_header">Css Classes</div></tr>\
			 		<tr class="control"><td>Add Class:</td><td><input id=css_addclass type="text"></td></tr>\
			 		<tr class="control"><td>Remove Class:</td><td><input id=css_delclass type="text"></td></tr>\
				</tbody></table>';

		$("#object_controls").append( $(str) );

		//
		// Control Functionality
		//		
		$("#all_selected_visible_input").each(function() {
			$(this).change(function(e) {
				obj.dprint("visible changed");
				var isChecked = ($("#all_selected_visible_input:checked").val() != null);
				
				for (var i in selectedObjs) {
					var selectedObj = selectedObjs[i];
					selectedObj.setIsVisible(isChecked);
					//$("#all_selected_visible_input:checked").attr('checked', isChecked);
				}
				
			});
		});
		
		$("#button_alignleft").click(function() {
			theCanvas().alignLeft();
		});
		$("#button_alignright").click(function() {
			theCanvas().alignRight();
		});
		$("#button_aligncenter").click(function() {
			theCanvas().alignCenter();
		});
		
		$("#button_aligntop").click(function() {
			theCanvas().alignTop();
		});
		$("#button_alignbottom").click(function() {
			theCanvas().alignBottom();
		});
		$("#button_alignmiddle").click(function() {
			theCanvas().alignMiddle();
		});
		$("#button_disthorizcenters").click(function() {
			theCanvas().distributeHorizontalCenters();
		});
		$("#button_distvertcenters").click(function() {
			theCanvas().distributeVerticalCenters();
		});
		$("#button_disthorizspace").click(function() {
			theCanvas().distributeHorizontalSpacebetween();
		});
		$("#button_distvertspace").click(function() {
			theCanvas().distributeVerticalSpacebetween();
		});
		
		//
		// Class controls
		// Set keyboard handlers for input boxes
		$("tr.control #css_addclass").keydown(function(e) {
			var key = e.keyCode;
			if (key == 13) {			
				for (var i in selectedObjs) {
					var selectedObj = selectedObjs[i];
					selectedObj.addClass($(this).val());
				}
				$(this).val("");
			}
		});
		$("tr.control #css_delclass").keydown(function(e) {
			var key = e.keyCode;
			if (key == 13) {
				for (var i in selectedObjs) {
					var selectedObj = selectedObjs[i];
					selectedObj.removeClass($(this).val());
				}
				$(this).val("");
			}
		});
		
	}
};

ControlPanel.prototype.loadCanvasControls = function() {

	if (theCanvas() != null) {

		var baseObject = theCanvas().getBaseObject();

		$("#canvas_header").remove();
		$("#canvas_controls").remove();
		$("#canvas_control_container").remove();		
		
		$("#tab_objectControls").append( $(
			'<div id="canvas_control_container" class="control_group_container">\
				<div id="canvas_header" class="control_header">Canvas: </div>\
				<div id="canvas_controls" class="control_group"></div>') );
		
		$("#canvas_header").append(theCanvas().getBaseObject().id);
		//$("#canvas_controls").append("<div class=\"control_header\">Canvas: " + theCanvas().getBaseObject().id + "</div>");
		
		var str = "<table><tbody>";
		
		/*
		for (var i=0; i<Canvas.attributes.length; i++) {
			var opt = Canvas.attributes[i];
	
			str += '<tr class="control">\
						<td class="control_label">'+ opt.name + '</td>\
						<td class="control_input"><input name="'+opt.name+'" type="text" value="'+ theCanvas().getBaseObject().attributes[opt.name].value + '"></td>\
					</tr>';
					
		}
		*/
	
			
		str += '<tr class="control">\
					<td class="control_label">id</td>\
					<td class="control_input"><input id="canvas_id_input" name="id" type="text" value="'+ baseObject.idName + '"></td>\
				</tr>';
		
		for (var attr in theCanvas().baseObject.attributes) {
			var opt = theCanvas().baseObject.attributes[attr];
	
			//if (opt.value != "") {
				str += '<tr class="control canvasattr">\
							<td class="control_label">'+ attr + '</td>\
							<td class="control_input"><input name="'+attr+'" type="text" value="'+ opt.value + '"></td>\
						</tr>';
			//}
					
		}
		
		str += "</tbody></table>";
		$("#canvas_controls").append( $(str) );
		
		
		$("#canvas_id_input").each(function() {
			$(this).keydown(function(e) {
				var key = e.keyCode;
				if (key == 13) {
					var value = $(this).val();
				
					baseObject.removeClass(baseObject.idName);
					baseObject.addClass(value);
					baseObject.setId(value);
				}
			});
		});
		
		$("tr.control.canvasattr input").each(function() {
			$(this).keydown(function(e) {
				var key = e.keyCode;
				if (key == 13) {
					var key = $(this).attr("name");
					var value = $(this).val();
				
					theCanvas().getBaseObject().setAttribute(key, value);
					
					// Set attribute updates the selected object controls,
					// not the canvas controls, so just do a full refresh for now
					//theControlPanel().fullRefresh();
				}
			});
		});
		
	}
};

ControlPanel.prototype.loadObjectList = function() {

	this.dprint("loadObjectList");
	
	$("#object_list_container").empty();

	if (theCanvas() != null) {
		this.dprint("loading objects");
	
		var str = '<div id="objectlist_list" class="objectlist_list" >';
	
		var numChildren = 0;
		for (var id in theCanvas().baseObject.children) {
			//this.dprint(".");
			
			numChildren++;
			var o = theCanvas().getBaseObject().children[id];
			
			str += '<div class="objectlist_element ' + 
					(o.isSelected ? " ui-selected" : "") + 
					(!o.isVisible ? " visible" : "") +
				'">' + o.id + 
				'<div class="objectlist_element_visibleicon">' +
					'<span class="ui-icon-eye"' + 
						(!o.isVisible ? 'style="display: none;"' : '') +
					'></span>' +
				'</div>' +
			'</div>';
		}

		if (numChildren == 0) {
			$("#object_list_container").hide();
			return;
		} else {
			$("#object_list_container").show();
		}
	
		str += '</div>';

		$("#object_list_container").append( $(
			'<div id="objectlist_header" class="control_header">Objects</div>\
			<div id="objectlist_controls" class="control_group"></div>') );
		
		$("#objectlist_controls").append(str);
		
		$(".objectlist_element").click(function(e) {
			
			var base_obj = theCanvas().baseObject;
			var obj_id = $(this).text(); // get id from div's text
			var obj = base_obj.children[obj_id];
			
			//$(this).toggleClass("ui-selected").siblings().removeClass("ui-selected");
			//base_obj.setSelectedObject(base_obj.children[obj_id]);
			
			var objs = null;
			if (e.shiftKey) {
				objs = base_obj.selectedObjects;
			} else {
				objs = [];
			}
			
			objs.push(obj);
			base_obj.setSelectedObjects(objs);
			
			
		});
		
		$(".objectlist_element_visibleicon").click(function() {
			var base_obj = theCanvas().baseObject;
			var obj_id = $(this).parent(".objectlist_element").text(); // get id from div's text
			var obj = base_obj.children[obj_id];
			
			obj.setIsVisible(!obj.isVisible);
			//$(this).children("img").toggle(obj.isVisible);
			$(this).children(".ui-icon-eye").toggle(obj.isVisible);
			
		});
		
		/*
		$("#objectlist_list").selectable({
			selected: function(event, ui) {
				
			}
		});
		*/
		
	}

};

ControlPanel.prototype.fullRefresh = function() {

	this.dprint("fullRefresh");

	this.loadObjectList();

	this.loadObjectControls();
	this.loadCanvasControls();	
	
	$(".control_header").unbind("click");
	
	$(".control_header").each(function() {
		$(this).click(function() {
			theControlPanel().dprint("toggle");			
			$(this).siblings("div").toggle();
		});
	});
	
	$("input").keydown(function(e) {
		e.stopPropagation();
	});
}

ControlPanel.prototype.objectAttributeChanged = function(name, value) {
	this.dprint("Object attribute changed: " + name + "->" + value);
	
	$("#object_controls input[name="+name+"]").val(value);
}

ControlPanel.prototype.canvasAttributeChanged = function(name, value) {
	this.dprint("Canvas attribute changed: " + name + "->" + value);
	
	$("#canvas_controls input[name="+name+"]").val(value);
}

ControlPanel.prototype.updateNavMap = function() {
	$("#nav_map").empty();
	
	if (theCanvas() != null) {
	
		var curObj = theCanvas().getBaseObject();
		
		$("#nav_map").prepend(">>" + curObj.id);
		while(curObj.parent != null) {
			$("#nav_map").prepend(">>" + curObj.parent.id);
			curObj = curObj.parent;
		}
		
	}
	//$("#nav_map").prepend("test");
};

// Debug output to console
ControlPanel.prototype.dprint = function(str) {
	if (ControlPanel.debug) {
		cprint(ControlPanel.className + ": " + str, "#0000ff");
	}
};
